import { Component } from 'react';
import { Carousel, Flex, Grid, Toast } from 'antd-mobile';
import axios from 'axios';

// 导入顶部搜索栏组件
import SearchHeader from '../../components/SearchHeader';

import './index.scss'

// 导入BASE_URL
import { BASE_URL } from "../../utils/url"; 

import Nav1 from '../../assets/images/nav-1.png'
import Nav2 from '../../assets/images/nav-2.png'
import Nav3 from '../../assets/images/nav-3.png'
import Nav4 from '../../assets/images/nav-4.png'

const navs = [
  {
    id: 1,
    img: Nav1,
    title: '整租',
    path: '/home/list',
    params: {
      rentType: 'true'
    }
  },
  {
    id: 2,
    img: Nav2,
    title: '合租',
    path: '/home/list',
    params: {
      rentType: 'false'
    }
  },
  {
    id: 3,
    img: Nav3,
    title: '地图找房',
    path: '/map'
  },
  {
    id: 4,
    img: Nav4,
    title: '去出租',
    path: '/rent/add'
  },
]

// 轮播图存在问题：
// 1. 不会自动播放
// 2. 从其他路由返回时高度显示有问题

// 原因： 轮播图动态加载，前后轮播图数据数组数量不一致
// 解决： 方案一： 将初始swipers数组设置长度与轮播图数量一致
//       方案二： 1. 在state中添加一个状态标志符，表示swipers数组是否加载完毕
//               2. 在数据加载完毕后将状态标志符置为true
//               3. 在渲染中添加判断语句，只有标识符为true才渲染走马灯结构

export default class Index extends Component {
  state = {
    swipers: [],
    imgHeight: 212,
    flag: false,
    // 租房小组数据
    groups: [],
    // 资讯数据
    news: [],
    // 当前定位城市名称
    myCityName: '定位城市',
    // 当前定位城市信息
    myCityData: {},
  }
  
  // 加载轮播图数据
  async getSwipers() {
    const imgurl = `${BASE_URL}/home/swiper`
    let res  = await axios({
      method: 'get',
      url: imgurl
    })
    this.setState({
      swipers: res.data.body,
      flag: true
    })
  }

  // 渲染轮播图结构
  renderSwipers() {
    return this.state.swipers.map(val => 
      <a
        key={val.id}
        href="http://www.alipay.com"
        style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
      >
        <img
          src={`${BASE_URL}${val.imgSrc}`}
          alt={val.alt}
          style={{ width: '100%', verticalAlign: 'top' }}
        />
      </a>
    )
  }

  // 渲染导航栏结构
  renderNavs() {
    return navs.map(val => (
      <Flex.Item  key={val.id} onClick={() => this.props.history.push({pathname: val.path, state: val.params || {}})}>
        <img src={val.img} alt=""/>
        <h2>{val.title}</h2>
      </Flex.Item>
    ))
  }

  // 渲染资讯页面
  renderNews() {
    return this.state.news.map(item => (
      <Flex key={item.id} onClick={() => {Toast.info('点了也没用，还没做呢...', 0.5, null, false)}}>
        <Flex.Item>
          <img src={`${BASE_URL}${item.imgSrc}`} alt="" style={{ width: '80%', height: '80%' }}/>
        </Flex.Item>
        <Flex.Item flex={3}>
          <div className="article">
            <h4>
              {item.title}
            </h4>
            <footer>
              <span>{item.from}</span>
              <span>{item.date}</span>
            </footer>
          </div>
        </Flex.Item>
      </Flex>
    ))
  }

  // 获取租房小组数据
  async getGroups() {
    const areaQuery = this.state.myCityData.value
    let res = await axios.get(`${BASE_URL}/home/groups?area=${areaQuery}`)
    this.setState({
      groups: res.data.body
    })
  }

  // 获取最新资讯数据
  async getNews() {
    const newsQuery = this.state.myCityData.value
    let res = await axios.get(`${BASE_URL}/home/news?area=${newsQuery}`)
    this.setState({
      news: res.data.body
    })
  }

  // 获取定位城市名称及信息
  async getCityData() {
    // 如果在本地存储中存在当前城市信息
    if (localStorage.getItem('hkzf_city') !== null) {
      var { label } = JSON.parse(localStorage.getItem('hkzf_city'))
    }
    
    if (label) {
      let myCityData = await axios.get(`${BASE_URL}/area/info?name=${label}`)
      this.setState({
        myCityName: label,
        myCityData
      })
    } else {
      // ip定位获取当前位置信息
      var myCity = new window.BMapGL.LocalCity();
      // 根据当前城市名称获取城市信息
      myCity.get(async res => {
        let myCityName = res.name.slice(0, -1)
        let myCityData = await axios.get(`${BASE_URL}/area/info?name=${res.name}`)
        let { label, value } = myCityData.data.body
        localStorage.setItem('hkzf_city', JSON.stringify({ label, value }))
        this.setState({
          myCityName,
          myCityData,
        })
      })
    }
  }

  componentDidMount() {
    this.getCityData()
    this.getSwipers()
    this.getGroups()
    this.getNews()
  }

  render() {
    return (
      <div>
        <SearchHeader myCityName={this.state.myCityName}></SearchHeader>
        <div className='index'>
          <div className="swipers">
            {
              this.state.flag ? (
              <Carousel
                autoplay
                autoplayInterval={3000}
                infinite
              >
                {this.renderSwipers()}
              </Carousel>
              ) : ''
            }
          </div>
          <Flex className="nav">
            {
              this.renderNavs()
            }
          </Flex>
          {/* 租房小组渲染区域 */}
          <div className="group">
            <div className="title">
              租房小组
              <span>更多</span>
            </div>
            <div className="grid">
              <Grid data={this.state.groups}
                columnNum={2}
                square={false}
                hasLine={false}
                renderItem={dataItem => (
                  <div style={{ margin: '0 12.5px', overflow: 'hidden' }} onClick={() => {Toast.info('点了也没用，还没做呢...', 0.5, null, false)}}>
                    <div style={{ float: 'left', color: '#888', textAlign: 'left' }}>
                      <div style={{ color: '#333', fontWeight: 'bold', marginBottom: '10px', fontSize: '13px'}}>{dataItem.title}</div>
                      <div style={{ fontSize: '12px' }}>{dataItem.desc}</div>
                    </div>
                    <img src={`${BASE_URL}${dataItem.imgSrc}`} style={{ float: 'right', width: '50px', height: '50px' }} alt="" />
                  </div>
                )}
              />
            </div>
          </div>
          <div className="news"> 
            <div className="newsTitle">
              <h3>最新资讯</h3>
            </div>
            <div className="newsBody">
              {
                this.renderNews()
              }
            </div>
          </div>
        </div>
      </div>
    );
  }
}